<script setup>
import { ref } from 'vue'
import api from '@/api'
import { showNotify } from 'vant'
import { useRouter, useRoute } from 'vue-router'
import useAuthStore from '@/store/auth'

const $route = useRoute()
const $router = useRouter()
const $authStore = useAuthStore()
const formType = ref(1) // 1验证码登录2账号密码登录

// 已登录，跳转首页
if ($authStore.isLogin()) {
  $router.replace($route.query.redirect || '/')
}

const formData1 = ref({
  username: '',
  sms_code: '',
  company_number: $route.query.id,
})

const formData2 = ref({
  username: '',
  password: '',
  company_number: $route.query.id,
})

const formData3 = ref({
  username: '',
  password: '',
  password_again: '',
})

const is_password = ref(1) // 0初始密码1非初始

const timeCountDownTop = ref('获取验证码')
const counting = ref(false)

const getCompanyInfo = async () => {
  try {
    const res = await api.get('/auth/company/' + $route.query.id)
    company.value = res.data
  } catch (error) {
    console.error(error)
  }
}

const loading = ref(false)
const loading2 = ref(false)

const company = ref()

const formSubmit = async () => {
  if (formType.value == 1) {
    if (!formData1.value.username) {
      showNotify({ type: 'danger', message: '请输入手机号' })
      return
    }
    if (!formData1.value.sms_code) {
      showNotify({ type: 'danger', message: '请输入验证码' })
      return
    }
    loading.value = true
    try {
      const res = await api.post('/auth/smsLogin', formData1.value)
      succeed(res)
    } catch (error) {
      console.error(error)
    }
    loading.value = false
  } else {
    if (!formData2.value.username) {
      showNotify({ type: 'danger', message: '请输入手机号' })
      return
    }
    if (!formData2.value.password) {
      showNotify({ type: 'danger', message: '请输入密码' })
      return
    }
    loading.value = true
    try {
      const res = await api.post('/auth/login', formData2.value)
      succeed(res)
    } catch (error) {
      console.error(error)
    }
    loading.value = false
  }
}

const formSubmit2 = async () => {
  var obj = { ...formData3.value }
  if (formType.value == 1) {
    obj.username = formData1.value.username
  } else {
    obj.username = formData2.value.username
  }
  if (!obj.password) {
    showNotify({ type: 'danger', message: '请输入新密码' })
    return
  }
  if (!obj.password_again) {
    showNotify({ type: 'danger', message: '请确认新密码' })
    return
  }
  if (obj.password != obj.password_again) {
    showNotify({ type: 'danger', message: '两次新密码输入不一致' })
    return
  }
  loading2.value = true
  try {
    const res = await api.post('/user/updateUserPassword', obj)

    $authStore.login(temporarilyInfo.value.data)
    $router.replace($route.query.redirect || '/')
  } catch (error) {
    console.error(error)
  }
  loading2.value = false
}

const temporarilyInfo = ref({
  data: {}
})

const succeed = (res) => {
  if (!res.data.is_password) {
    // 初始密码需要修改
    is_password.value = 0
    temporarilyInfo.value = res
  } else {
    $authStore.login(res.data)
    $router.replace($route.query.redirect || '/')
  }
}

const getCode = async () => {
  if (counting.value) {
    return false
  }
  if (!formData1.value.username) {
    showNotify({ type: 'danger', message: '请输入手机号' })
    return
  }
  try {
    const res = await api.post('/auth/sendCode', {
      phone: formData1.value.username,
      event: 'user_login',
    })
    showNotify({ type: 'success', message: res.message })
    console.log('res', res)
    countDown(60)
  } catch (error) {
    console.error(error)
  }
}

// 验证码倒计时
const countDown = (count) => {
  let that = this
  if (count === 0) {
    timeCountDownTop.value = '获取验证码'
    counting.value = false
    return false
  }
  counting.value = true
  timeCountDownTop.value = count + 's'
  setTimeout(function () {
    count--
    countDown(count)
  }, 1000)
}

const switchFormType = async (e) => {
  formType.value = e
}

if ($route.query.id) {
  getCompanyInfo()
}
</script>

<template>
  <div class="page-login">
    <template v-if="is_password">
      <van-form class="form-login"
                @submit="formSubmit">
        <!-- <div class="mb50">
        <img class="logo"
             v-if="company && company.logo"
             :src="company.logo" />
        <div class="title">{{ company ? '五月石榴' : '企业' }}智学系统</div>
        <div class="subtitle"
             v-if="company">{{ company.name }}</div>
      </div> -->

        <div class="mb50">
          <img class="logo"
               v-if="company && company.logo"
               :src="company.logo" />
          <div class="title">{{ company ? '五月石榴' : '企业' }}智学系统</div>
          <div class="subtitle"
               v-if="company">{{ company.name }}</div>
        </div>
        <van-cell-group v-if="formType==1"
                        inset>
          <van-field v-model="formData1.username"
                     type="number"
                     label="手机号"
                     name="username"
                     placeholder="输入手机号" />
          <van-field v-model="formData1.sms_code"
                     label="验证码"
                     name="sms_code"
                     type="number"
                     placeholder="输入验证码">
            <template #button>
              <div class="btn_div">
                <van-button @click="getCode"
                            size="mini"
                            type="primary">{{timeCountDownTop}}</van-button>
              </div>
            </template>
          </van-field>
        </van-cell-group>
        <van-cell-group v-if="formType==2"
                        inset>
          <van-field v-model="formData2.username"
                     type="number"
                     label="手机号"
                     name="username"
                     placeholder="输入手机号" />
          <van-field v-model="formData2.password"
                     label="密码"
                     name="login_password"
                     type="password"
                     placeholder="输入密码" />
        </van-cell-group>
        <div v-if="formType==1"
             @click="switchFormType(2)"
             class="switch_text">
          账号密码登录
          <van-icon name="arrow" />
        </div>
        <div v-if="formType==2"
             @click="switchFormType(1)"
             class="switch_text">
          验证码登录
          <van-icon name="arrow" />
        </div>
        <div class="footer">
          <van-button block
                      type="primary"
                      native-type="submit"
                      :loading="loading">登录</van-button>
        </div>

      </van-form>
    </template>

    <template v-else>
      <van-form class="form-login"
                @submit="formSubmit2">
        <div class="mb50">
          <div class="title">修改密码</div>
        </div>

        <van-cell-group inset>
          <van-field v-model="formData3.password"
                     type="password"
                     label="新密码"
                     name="username"
                     placeholder="输入新密码" />
          <van-field v-model="formData3.password_again"
                     label="确认新密码"
                     name="login_password"
                     type="password"
                     placeholder="输入新密码" />
        </van-cell-group>

        <div class="footer">
          <van-button block
                      type="primary"
                      native-type="submit"
                      :loading="loading2">确认</van-button>
        </div>
      </van-form>
    </template>
  </div>
</template>

<style scoped lang="scss">
.page-login {
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  background: #f7f8fa;
  .form-login {
    width: 100%;
  }
  .logo {
    display: block;
    height: 90px;
    margin: 0 auto;
    border-radius: 4px;
    margin-top: -150px;
    margin-bottom: 50px;
  }
  .title {
    color: #1d2129;
    font-size: 22px;
    text-align: center;
  }
  .subtitle {
    color: #86909c;
    font-size: 16px;
    text-align: center;
    margin-top: 8px;
  }
  .footer {
    padding: 16px;
    margin-top: 4px;
  }
}

.mb50 {
  margin-bottom: 50px;
}

.switch_text {
  padding: 0 16px;
  margin-top: 20px;
  font-size: 12px;
  color: #aaa;
}

.btn_div {
  position: relative;
  height: 24px;
  top: -4px;
}
</style>
